<?php

namespace gl;

/*
|--------------------------------------------------------------------------
| 自定义全局公共函数库，放置在gl命名空间下
|--------------------------------------------------------------------------
|一些辅助函数，自己定义
*/


/**
 * 获取一个唯一不重复的字符串，利用php提供的uniqid函数实现
 * @return mixed
 */
function get_unique()
{
    return str_replace('.', '', uniqid('', true));
}

/**
 * 将文件尺寸转换为易读的单位 比如:readable_filesize(1203, 2) 输出1.17Kb
 * @param $bytes 字节大小
 * @param $decimals 保留的位数
 * @return string
 */
function readable_filesize($bytes, $decimals = 2)
{
    $size  = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
    $floor = floor((strlen($bytes) - 1) / 3);
    return sprintf("%.{$decimals}f", $bytes / pow(1024, $floor)) . $size[$floor];
}

/**
 * 按指定长度截取字符串字符串，用指定字符串代替
 * @param $str
 * @param null $length
 * @return string
 */
function str_ellipsis($str, $length = null, $replaced = '......')
{
    if (mb_strlen($str) > $length) {
        return mb_substr($str, 0, $length) . $replaced;
    }
    return $str;
}

function clear_str_ellipsis($str, $length = null, $replaced = '......')
{
    return trim(str_replace('&nbsp;', '', \gl\str_ellipsis(strip_tags($str), $length, $replaced)));
}

/**
 * 删除目录或者文件
 * @param  string $path
 * @param  boolean $is_del_dir
 * @return fixed
 */
function del_dir_or_file($path, $is_del_dir = FALSE)
{
    $handle = opendir($path);
    if ($handle) {
        // $path为目录路径
        while (false !== ($item = readdir($handle))) {
            // 除去..目录和.目录
            if ($item != '.' && $item != '..') {
                if (is_dir("$path/$item")) {
                    // 递归删除目录
                    la_del_dir_or_file("$path/$item", $is_del_dir);
                } else {
                    // 删除文件
                    unlink("$path/$item");
                }
            }
        }
        closedir($handle);
        if ($is_del_dir) {
            // 删除目录
            return rmdir($path);
        }
    } else {
        if (file_exists($path)) {
            return unlink($path);
        } else {
            return false;
        }
    }
}

/**
 * 判断是否是合法的手机格式
 * @param $string
 * @return int
 */
function is_mobile($string)
{
    return preg_match('/^1[345678]+\d{9}$/', $string);
}

//电话
function isPhone($string)
{
    return preg_match('/\d{8,18}$/', $string);
}

/**
 * 判断是否合法的邮箱
 * @param $str
 * @return bool
 */
function is_email($str)
{
    return (filter_var($str, FILTER_VALIDATE_EMAIL) === false) ? false : true;
}

/**
 * 设置一个密码强度等级规则，依次返回不同等级，返回的值越大，代表密码复杂度越强
 * @param $str
 * @return int
 */
function codes($str)
{
    $score = 0;
    if (preg_match("/[0-9]+/", $str)) {
        $score++;
    }
    if (preg_match("/[0-9]{3,}/", $str)) {
        $score++;
    }
    if (preg_match("/[a-z]+/", $str)) {
        $score++;
    }
    if (preg_match("/[a-z]{3,}/", $str)) {
        $score++;
    }
    if (preg_match("/[A-Z]+/", $str)) {
        $score++;
    }
    if (preg_match("/[A-Z]{3,}/", $str)) {
        $score++;
    }
    if (preg_match("/[_|\-|+|=|*|!|@|#|$|%|^|&|(|)]+/", $str)) {
        $score += 2;
    }
    if (preg_match("/[_|\-|+|=|*|!|@|#|$|%|^|&|(|)]{3,}/", $str)) {
        $score++;
    }
    if (strlen($str) >= 10) {
        $score++;
    }
    return $score;
}

/**
 * 用常规方式发送邮件，依赖PHPMailer扩展包
 *
 * @param string $to
 * @param string $subject
 * @param string $body
 * @param string $name
 * @param array $attachment
 *
 * @return mixed
 */
function send_mail($to = null, $subject = '', $body = '', $name = '', $attachment = null, $file_name = null)
{
    $from_email = config('mail.from.address');
    $from_name  = config('mail.from.name');;
    $reply_email   = null;
    $reply_name    = '美吉生物';
    $mail          = new \PHPMailer\PHPMailer\PHPMailer();
    $mail->CharSet = 'UTF-8'; //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
    $mail->IsSMTP(); // 设定使用SMTP服务
    $mail->SMTPDebug = 0; // 关闭SMTP调试功能
    // 1 = errors and messages
    // 2 = messages only
    $mail->SMTPAuth   = true; // 启用 SMTP 验证功能
    $mail->SMTPSecure = ''; // 使用安全协议
    $mail->Host       = config('mail.host'); // SMTP 服务器
    $mail->Port       = config('mail.port'); // SMTP服务器的端口号
    $mail->SMTPSecure = config('mail.encryption');
    $mail->Username   = config('mail.username'); // SMTP服务器用户名
    $mail->Password   = config('mail.password'); // SMTP服务器密码
    $mail->SetFrom($from_email, $from_name);
    $replyEmail = $reply_email ? $reply_email : $from_email;
    $replyName  = $reply_name ? $reply_name : $from_name;
    $rec        = array();//接收人s
    if (empty($to)) {
        return '缺少收件人';
        //$rec[] = C('EMAIL_SMTP_USERNAME'); //邮件地址为空时，默认使用后台默认邮件测试地址
    }
    if (is_string($to)) {
        if (is_email($to)) {
            $rec[] = $to;
        }
    }
    if (is_array($to)) {
        foreach ($to as $tt) {
            if (is_email($tt)) {
                $rec[] = $tt;
            }
        }
    }
//    if ($name == '') {
//        $name = C('PAGE_TITLE'); //发送者名称为空时，默认使用网站名称
//    }
//    if ($subject == '') {
//        $subject = C('PAGE_TITLE'); //邮件主题为空时，默认使用网站标题
//    }
//    if ($body == '') {
//        $body = C('PAGE_TITLE'); //邮件内容为空时，默认使用网站描述
//    }
    $mail->AddReplyTo($replyEmail, $replyName);
    $mail->Subject = $subject;
    $mail->MsgHTML($body); //解析
    foreach ($rec as $_to) {
        $mail->AddAddress($_to, $name);
    }
    if (is_array($attachment)) { // 添加附件
        foreach ($attachment as $file) {
            is_file($file) && $mail->AddAttachment($file, $file_name);
        }
    }
    if ($mail->Send()) {
        return array('st' => true, 'msg' => '邮件发送成功');
    } else {
        return array('st' => false, 'msg' => $mail->ErrorInfo);
    }
}

/**
 * 发送手机短信
 */

function send_sms($mobile = '', $content = '')
{
    $url       = "http://sms.106jiekou.com/utf8/sms.aspx";
    $post_data = "account=lei.zhang&password=sg_sms_201414&mobile=" . $mobile . "&content=" . rawurlencode($content);
    $curl      = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_NOBODY, true);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
    $return_str = curl_exec($curl);
    curl_close($curl);
    //短信返回结果信息
    $status = array(
        '100' => '发送成功',
        '101' => '验证失败',
        '102' => '手机号码格式不正确',
        '103' => '会员级别不够',
        '104' => '内容未审核',
        '105' => '内容过多',
        '106' => '账户余额不足',
        '107' => 'Ip受限',
        '108' => '手机号码发送太频繁，请换号或隔天再发',
        '109' => '帐号被锁定',
        '110' => '手机号发送频率持续过高，黑名单屏蔽数日',
        '120' => '系统升级',
    );
    if ($return_str == '100') {
        return array('code' => 'ok', 'msg' => $status[$return_str]);
    } else {
        return array('code' => 'err', 'msg' => $status[$return_str]);
    }
}

/**
 * 把文件打包成为zip
 * @param  array $files 需要打包在同一个zip中的文件的路径
 * @param  string $out_dir zip的文件的输出目录
 * @param  [type] $des_name   zip文件的名称m
 * @return boolean            打包是否成功
 */
function zip($files, $file_path, $out_dir, $des_name)
{
    $zip = new \ZipArchive;
    // 创建文件夹
    mkdir($out_dir);
    // 打包操作
    $result = $zip->open($out_dir . '/' . $des_name, ZipArchive::CREATE);
    if (true !== $result) {
        return false;
    }

    foreach ($files as $file) {
        // 添加文件到zip包中
        $zip->addFile($file_path . '/' . $file,
            str_replace('/', '', $file));
    }
    $zip->close();
    return true;
}

/**
 * 解压zip文件
 * @param  string $zip_file 需要解压的zip文件
 * @param  string $out_dir 解压文件的输出目录
 * @return boolean          解压是否成功
 */
function unzip($zip_file, $out_dir)
{
    $zip = new \ZipArchive();
    if (true !== $zip->open($zip_file)) {
        return false;
    }
    $zip->extractTo($out_dir);
    $zip->close();
    return true;
}

/**
 * 截取干净字符串
 * @param $str
 * @param int $len
 * @param string $suffix
 * @return bool|mixed|string
 */
function getSubStrEllipsis($str, $len = 62, $suffix = ' ...')
{
    $str = trim(strip_tags($str));
    $str = str_replace(array("\r\n", "\r", "\n"), '', $str);
    $str = preg_replace('/\s(?=\s)/', '', $str);
    if (strlen($str) <= $len) {
        return $str;
    }
    $str = substr($str, 0, $len);
    return $str . $suffix;
}

/**
 * 把字符串变换成seo格式
 * @param $string
 * @param int $limit
 * @return array|string
 */
function the_seo_filter($string, $limit = 1)
{
    $retval         = $string;
    $pattern        = '/[\p{P}\p{S}]/u';
    $pattern_letter = '/[!"#$%&\'()*+,.\/:;<=>?@[\\\]^_`{|}~]/';
    $retval         = preg_replace($pattern, '', strtolower($retval));
    $retval         = preg_replace($pattern_letter, '', $retval);
    $retval         = preg_replace('/\s/', '-', $retval);
    $foo            = explode('-', $retval);
    foreach ($foo as $value) {
        switch (true) {
            case (strlen($value) <= $limit):
                continue;
            default:
                $container[] = $value;
                break;
        }
    }
    $container = (sizeof($container) > 0 ? implode('-', $container) : $string);
    return $container;
}

/**
 * 得到一个网址的主域名
 * @param string $url
 * @return bool
 */
function get_url_domain($url = '')
{
    $url = trim($url);
    if ($url == '') {
        return false;
    }
    $pieces = parse_url($url);
    $domain = isset($pieces['host']) ? $pieces['host'] : '';
    if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
        return $regs['domain'];
    }
    return false;
}

/**
 * 获取文件夹中的文件列表
 * @param $dir
 * @param string $pre
 * @return array
 */
function get_dir_file($dir, $pre = '')
{
    $dir       = $_SERVER['DOCUMENT_ROOT'] . $dir;
    $fileArray = array();
    if (is_dir($dir)) {

        if (false != ($handle = opendir($dir))) {
            $i = 0;
            while (false !== ($file = readdir($handle))) {
                //去掉"“.”、“..”以及带“.xxx”后缀的文件
                if ($file != "." && $file != ".." && strpos($file, ".")) {
                    $fileArray[$i] = $pre . $file;
                    $i++;
                }
            }
            //关闭句柄
            closedir($handle);
        }
    }
    return $fileArray;
}

/**
 * 把xml文件解析成数组
 * @param $file
 * @param bool $type
 * @param bool $returnArray
 * @return mixed|null
 */
function xml_to_array($file, $type = false, $returnArray = true)
{
    $file = trim($file);
    if ($type) {
        if (!is_file($file)) {
            return null;
        }
        $str = simplexml_load_file($file);
    } else {
        if ($file == '') {
            return null;
        }
        $str = simplexml_load_string($file);
    }
    return json_decode(json_encode($str), $returnArray);
}

/**
 * 对查询结果集进行排序
 * @param array $list 查询结果
 * @param string $field 排序的字段名
 * @param string $sortby 排序类型 asc正向排序 desc逆向排序 nat自然排序
 * @return array
 */
function list_sort_by($list, $field, $sortby = 'asc')
{
    if (is_array($list)) {
        $refer = $resultSet = array();
        foreach ($list as $i => $data)
            $refer[$i] = &$data[$field];
        switch ($sortby) {
            case 'asc': // 正向排序
                asort($refer);
                break;
            case 'desc':// 逆向排序
                arsort($refer);
                break;
            case 'nat': // 自然排序
                natcasesort($refer);
                break;
        }
        foreach ($refer as $key => $val)
            $resultSet[] = &$list[$key];
        return $resultSet;
    }
    return false;
}

/**
 * 把返回的数据集转换成Tree
 * @param array $list 要转换的数据集
 * @param string $pk
 * @param string $pid parent标记字段
 * @param string $child 子数组标记
 * @param int $root
 * @return array
 */
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = 'child', $root = 0)
{
    // 创建Tree
    $tree = array();
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent           =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}

/**
 * 将list_to_tree的树还原成列表
 * @param  array $tree 原来的树
 * @param  string $child 孩子节点的键
 * @param  string $order 排序显示的键，一般是主键 升序排列
 * @param  array $list 过渡用的中间数组，
 * @return array        返回排过序的列表数组
 */
function tree_to_list($tree, $child = 'child', $order = 'id', &$list = array())
{
    if (is_array($tree)) {
        foreach ($tree as $key => $value) {
            $reffer = $value;
            if (isset($reffer[$child])) {
                unset($reffer[$child]);
                tree_to_list($value[$child], $child, $order, $list);
            }
            $list[] = $reffer;
        }
        $list = list_sort_by($list, $order, $sortby = 'asc');
    }
    return $list;
}

/**
 * 把多维数组转化成一维数组
 *
 * @param array $arr 需要转换的数组，必须有相同的子节点
 * @param string $sub 子节点名称
 * @param array &$rs 返回的引用数组
 *
 * @return array
 */
function float_array($arr = array(), $sub = '_sub', &$rs)
{
    if (empty($arr)) {
        return false;
    }
    foreach ($arr as $v) {
        $tmp2 = $v;
        if (isset($tmp2[$sub])) {
            unset($tmp2[$sub]);
            $rs[] = $tmp2;
            float_array($v[$sub], $sub, $rs);
        } else {
            $rs[] = $v;
        }
    }
}

/**
 * 格式化字节大小
 * @param  number $size 字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '')
{
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}

/**
 * 随机字符
 * @param int $len
 * @param int $type
 * @param null $addChars
 * @return string
 */
function rand_str($len = 6, $type = 3, $addChars = null)
{
    $str = '';
    switch ($type) {
        case 1:
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' . $addChars;
            break;
        case 2:
            $chars = str_repeat('0123456789', 3);
            break;
        case 3:
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' . $addChars;
            break;
        case 4:
            $chars = 'abcdefghijklmnopqrstuvwxyz' . $addChars;
            break;
        default :
            $chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789' . $addChars;
            break;
    }
    if ($len > 10) {
        $len = 10;
    }
    $charLen = strlen($chars) - 1;
    for ($i = 0; $i < $len; $i++) {
        $str .= $chars[mt_rand(0, $charLen)];
    }
    return $str;
}

/**
 * 隐藏手机号部分
 * @param $mobile
 * @return string
 */
function hidden_mobile($mobile)
{
    $start = substr($mobile, 0, 3);
    $end   = substr($mobile, -3);
    return $start . '***' . $end;
}

/**
 * 隐藏邮箱的部分
 * @param $email
 * @return string
 */
function hidden_email($email)
{
    $arr   = explode('@', $email);
    $start = substr($arr[0], 0, 3);
    $end   = substr($arr[0], -3);
    return $start . '***' . $end . $arr[1];
}

/**
 * 通过get方式投递数据
 * @param type $request_url
 * @return boolean
 */
function get_data($request_url)
{
    $ch = curl_init($request_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $res = curl_exec($ch);

    if ($error = curl_error($ch)) {
        exit(curl_error($ch));
        return false;
    }
    curl_close($ch);
    $res = json_decode($res, true);
    return $res;
}

/**
 * 采用post方式，投递数据到指定服务器
 * @param type $data
 * @param type $request_url
 * @return boolean
 */
function post_data($data, $request_url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $request_url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $res = curl_exec($ch);

    if ($error = curl_error($ch)) {
        exit(curl_error($ch));
        return false;
    }
    curl_close($ch);
    //$res = json_decode($res, true);
    return $res;
}

/**
 * 通过出生日期获取准确生日
 * @param type $birthday
 * @return type
 */
function get_age($birthday)
{
    $age = date('Y', time()) - date('Y', strtotime($birthday)) - 1;
    if (date('m', time()) == date('m', strtotime($birthday))) {
        if (date('d', time()) > date('d', strtotime($birthday))) {
            $age++;
        }
    } elseif (date('m', time()) > date('m', strtotime($birthday))) {
        $age++;
    }
    return $age;
}

/**
 * 获取用户浏览器型号
 */
function get_browser()
{
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'Maxthon')) {
        $browser = 'Maxthon';
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 12.0')) {
        $browser = 'IE12.0';
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 11.0')) {
        $browser = 'IE11.0';
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 10.0')) {
        $browser = 'IE10.0';
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 9.0')) {
        $browser = 'IE9.0';
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 8.0')) {
        $browser = 'IE8.0';
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 7.0')) {
        $browser = 'IE7.0';
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6.0')) {
        $browser = 'IE6.0';
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'NetCaptor')) {
        $browser = 'NetCaptor';
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Netscape')) {
        $browser = 'Netscape';
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Lynx')) {
        $browser = 'Lynx';
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Opera')) {
        $browser = 'Opera';
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome')) {
        $browser = 'Google';
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Firefox')) {
        $browser = 'Firefox';
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Safari')) {
        $browser = 'Safari';
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'iphone') || strpos($_SERVER['HTTP_USER_AGENT'], 'ipod')) {
        $browser = 'iphone';
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'ipad')) {
        $browser = 'iphone';
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'android')) {
        $browser = 'android';
    } else {
        $browser = 'other';
    }
    return $browser;
}

/**
 * 获取 IP  地理位置
 * 淘宝IP接口
 * @Return: array
 */
function get_address_by_ip($ip)
{
    $url    = "http://ip.taobao.com/service/getIpInfo.php?ip=" . $ip;
    $ipinfo = json_decode(file_get_contents($url));
    if ($ipinfo->code == '1') {
        return false;
    }
//    $city = $ipinfo->data->region . $ipinfo->data->city; //省市县
//    $ip   = $ipinfo->data->ip; //IP地址
//    $ips  = $ipinfo->data->isp; //运营商
//    $guo  = $ipinfo->data->country; //国家
//    if ($guo == '中国') {
//        $guo = '';
//    }
    return $ipinfo->data;
}

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function get_client_ip($type = 0, $adv = false)
{
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL) return $ip[$type];
    if ($adv) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) unset($arr[$pos]);
            $ip = trim($arr[0]);
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/**
 * 本函数将一个excel表格转换成一个二维数组,本函数依赖 phpoffice
 * 以表格的行编号为根键，列编号为第二维键名，表格内容为值
 * @param type $filepath excel文件全路径名
 * @param type $sheet 工作表编号，默认为0
 * @param type $beginRow 从excel的哪一行开始取数据，默认为第二行
 * @return type array
 */
function get_array_from_excel($filepath, $limit = null, $beginRow = 2, $sheet = null)
{
    if (!$sheet) {
        $sheet = 0;
    }
    $objPHPExcel  = \PHPExcel_IOFactory::load($filepath);
    $currentExcel = $objPHPExcel->getSheet($sheet);
    if (!$limit) {
        $rowCount = $currentExcel->getHighestRow(); //excel行数
    } else {
        $rowCount = $limit;
    }

    $colCount = $currentExcel->getHighestColumn();
    $data     = array();
    for ($rowIndex = $beginRow; $rowIndex <= $rowCount; $rowIndex++) {
        for ($colIndex = 'A'; $colIndex <= $colCount; $colIndex++) {
            $addr = $colIndex . $rowIndex;
            $cell = $currentExcel->getCell($addr)->getValue();
            if ($cell instanceof \PHPExcel_RichText) {
                $cell = $cell->__toString();
            }
            $data[$rowIndex][$colIndex] = $cell;
        }
    }
    return $data;
}

/**
 * 读取excel成二维数组
 *
 * @param string $xls_path 表格路径
 * @param array $sheets 需要读取哪几个sheet,默认第一个0
 * @param string $type 驱动 (Excel5读取xls   |   Excel2007读取xlsx)
 *
 * @return mixed
 */
function read_excel_to_array($xls_path = '', $sheets = array(0), $type = 'Excel2007')
{
    $xls_path = trim($xls_path);
    if (!is_file($xls_path)) {
        return false;
    }
    if (empty($sheets)) {
        return false;
    }
    $reader = \PHPExcel_IOFactory::createReader($type);
    $obj    = $reader->load($xls_path);
    foreach ($sheets as $s) {
        $datas['sheet_' . $s] = $obj->getSheet($s)->toArray();
    }
    return $datas;
}

/**
 * 由二维数组生成xls，并下载，依赖PHPExcel
 *
 * @param array $datas 数据
 * @param string $save_name 保存名称
 * @param string $type 驱动 (Excel5生成xls   |   Excel2007生成xlsx)
 * @param array $cell_color array( array('cell'=>'A1', 'color'=>'F28A8C') )
 *
 * @return void
 */
function output_excel_from_array($datas = array(), $save_name = '', $type = 'Excel5', $cell_color = array())
{
    if (empty($datas)) {
        return;
    }
    $save_name = trim($save_name);
    if ($save_name == '') {
        $save_name = date('Y-m-d_H-i');
    }

    // Create new PHPExcel object
    $objPHPExcel = new \PHPExcel();

    // Set document properties
    $objPHPExcel->getProperties()->setCreator("major")
        ->setLastModifiedBy("major")
        ->setTitle("Document")
        ->setSubject("Document")
        ->setDescription("major")
        ->setKeywords("major")
        ->setCategory("major");

    $objPHPExcel->setActiveSheetIndex(0);

    $objPHPExcel->getActiveSheet()->fromArray($datas);

    //设置背景颜色
    if (!empty($cell_color)) {
        foreach ($cell_color as $cc) {
            $cc['cell']  = trim($cc['cell']);
            $cc['color'] = trim($cc['color']);
            if ($cc['cell'] == '' && $cc['color'] == '') {
                continue;
            }
            $objPHPExcel->getActiveSheet()->getStyle($cc['cell'])->getFill()->applyFromArray(array(
                'type'       => PHPExcel_Style_Fill::FILL_SOLID,
                'startcolor' => array(
                    'rgb' => $cc['color']
                )
            ));
        }
    }

    $objPHPExcel->getActiveSheet()->setTitle($save_name);

    $hz = ($type == 'Excel2007') ? 'xlsx' : 'xls';

    ob_end_clean();
    // Redirect output to a client’s web browser (Excel5)
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="' . $save_name . '.' . $hz . '"');
    header('Cache-Control: max-age=0');
    // If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');
    // If you're serving to IE over SSL, then the following may be needed
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
    header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header('Pragma: public'); // HTTP/1.0

    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, $type);
    $objWriter->save('php://output');
    exit;
}

/**
 * 由二维数组生成xls，并下载
 *
 * @param array $sheets = array(array(...), array(...), ..., =>array(...))
 * @param string $save_name 保存名称
 * @param string $driver 驱动 (Excel5生成xls   |   Excel2007生成xlsx)
 *
 * @return void
 */
function output_excel_multi_sheet_from_array($sheets = array(), $save_name = '', $driver = 'Excel2007')
{
    if (empty($sheets)) {
        return;
    }
    $save_name = trim($save_name);
    if ($save_name == '') {
        $save_name = date('Y-m-d_H-i');
    }


    // Create new PHPExcel object
    $objPHPExcel = new \PHPExcel();

    // Set document properties
    $objPHPExcel->getProperties()->setCreator("major")
        ->setLastModifiedBy("major")
        ->setTitle("Document")
        ->setSubject("Document")
        ->setDescription("major")
        ->setKeywords("major")
        ->setCategory("major");

    $ki = 0;
    foreach ($sheets as $sheet) {
        if ($ki > 0) {
            $objPHPExcel->createSheet($ki);
        }
        $objPHPExcel->setActiveSheetIndex($ki);
        $objPHPExcel->getActiveSheet()->fromArray($sheet);
        $ki++;
        $objPHPExcel->getActiveSheet()->setTitle("sheet" . $ki);
    }

    $hz = ($driver === 'Excel2007') ? 'xlsx' : 'xls';

    ob_end_clean();
    // Redirect output to a client’s web browser (Excel5)
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="' . $save_name . '.' . $hz . '"');
    header('Cache-Control: max-age=0');
    // If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');
    // If you're serving to IE over SSL, then the following may be needed
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
    header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header('Pragma: public'); // HTTP/1.0

    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, $driver);
    $objWriter->save('php://output');
    exit;
}

/**
 * 按照key组合数组
 *
 * @param    array
 * @param    string
 *
 * @return   array
 **/
function array_group($array, $key)
{
    if (empty($array)) {
        return array();
    }

    $array1 = array();

    foreach ($array as $val) {
        $array1[$val[$key]][] = $val;
    }

    return $array1;
}


/**
 * 获取指定的键值
 *
 * @param    array
 * @param    string
 *
 * @return   array
 */
function get_single_key($array, $key)
{
    $infos = array();
    if (empty($array)) {
        return $infos;
    }
    foreach ($array as $val) {
        isset($val[$key]) && $infos[] = $val[$key];
    }

    return $infos;
}


/**
 * 按照key组合数组
 *
 * @param    array
 * @param    string
 *
 * @return   array
 **/
function single_group($array, $key)
{
    if (empty($array)) {
        return array();
    }

    $array1 = array();

    foreach ($array as $val) {
        $array1[$val[$key]] = $val;
    }

    return $array1;
}

/**
 * 判断两个数组的值是否相等
 * @param $array1
 * @param $array2
 * @return bool
 */
function array_equal($array1, $array2)
{
    $diff1 = array_diff($array1, $array2);
    $diff2 = array_diff($array2, $array1);
    if (!$diff1 && !$diff2) {
        return true;
    }
    return false;
}

/**
 * 数字转换为中文价格
 *
 * @param int
 *
 * @return string
 */
function cny($ns)
{
    static $cnums = array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"),
    $cnyunits = array("圆", "角", "分"),
    $grees = array("拾", "佰", "仟", "万", "拾", "佰", "仟", "亿");
    list($ns1, $ns2) = explode(".", $ns, 2);
    $ns2 = array_filter(array($ns2[1], $ns2[0]));
    $ret = array_merge($ns2, array(implode("", _cny_map_unit(str_split($ns1), $grees)), ""));
    $ret = implode("", array_reverse(_cny_map_unit($ret, $cnyunits)));
    return str_replace(array_keys($cnums), $cnums, $ret);
}

function _cny_map_unit($list, $units)
{
    $ul = count($units);
    $xs = array();
    foreach (array_reverse($list) as $x) {
        $l = count($xs);
        if ($x != "0" || !($l % 4)) $n = ($x == '0' ? '' : $x) . ($units[($l - 1) % $ul]);
        else $n = is_numeric($xs[0][0]) ? $x : '';
        array_unshift($xs, $n);
    }
    return $xs;
}

function url($url)
{
    $parse_uri = parse_url($url);
    $glue      = '?';
    if (isset($parse_uri['query'])) {
        $glue = '&';
    }
    $county    = null;
    $community = null;
    if (isset($_GET['county'])) {
        $county = $_GET['county'];
    }
    if (isset($_GET['community'])) {
        $community = $_GET['community'];
    }
    return $url . $glue . http_build_query(compact('county', 'community'));
}

/**
 * 判断用户是否禁用
 * @param $user
 * @return bool
 */
function user_is_disabled($user)
{
    if ($user->disabled_duration && $user->disabled_at) {
        $duration = $user->disabled_duration * 24 * 3600;
        $disabled_time = strtotime($user->disabled_at);
        $disabled_duration_time = $disabled_time + $duration;
        if ($disabled_duration_time > time()) {
            return true;
        }
    }
    return false;
}
